
package ch.hearc.coursJava.GUI.j2D.images;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;

import ch.hearc.coursJava.GUI.j2D.tools.JPanelDessin_A;

public class JPanelImages extends JPanelDessin_A
	{

	/*------------------------------------------------------------------*\
	|*							Constructeurs							*|
	\*------------------------------------------------------------------*/

	public JPanelImages()
		{
		this.compteur = 0;
		addListener();
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Public							*|
	\*------------------------------------------------------------------*/

	@Override
	protected void dessiner(Graphics2D g2d)
		{
		g2d.drawImage(image, 0, 0, w, h, null);

		}

	/*------------------------------------------------------------------*\
	|*							Methodes Private						*|
	\*------------------------------------------------------------------*/

	private void createImage()
		{
		this.w = this.getSize().width;
		this.h = this.getSize().height;
		this.image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		}

	private void addListener()
		{
		addComponentListener(new ComponentAdapter()
			{

				@Override
				public void componentResized(ComponentEvent e)
					{
					if (threadAnimation != null)
						{
						threadAnimation.stop();
						while(threadAnimation.isAlive())
							{
							try
								{
								Thread.sleep(100);
								}
							catch (InterruptedException e1)
								{
								e1.printStackTrace();
								}
							}
						}

					createImage();
					animerImage();
					}
			});
		}

	private void animerImage()
		{
		threadAnimation = new Thread(new Runnable()
			{

				@Override
				public void run()
					{
					compteur++;
					threadAnimation.setName("Thread animation " + compteur);
					System.out.println(Thread.currentThread().getName());

					float dh = 1 / (float)h;
					float hueInit = 0;

					while(true)
						{
						fillImage(hueInit);
						repaint();
						hueInit += dh;

						if (hueInit >= 1)
							{
							hueInit = 0;
							}
						}
					}

			});

		threadAnimation.start();

		}

	private void fillImage(float hueInit)
		{
		float dh = 1 / (float)h;
		float hue01 = hueInit;

		for(int j = 1; j <= h; j++)
			{
			for(int i = 1; i <= w; i++)
				{
				int rgb = Color.HSBtoRGB(hue01, 1, 1);
				image.setRGB(i - 1, j - 1, rgb);
				}
			hue01 += dh;
			}
		}

	/*------------------------------------------------------------------*\
	|*							Attributs Private						*|
	\*------------------------------------------------------------------*/

	//Tools
	private BufferedImage image;
	private int w;
	private int h;
	private Thread threadAnimation;
	private int compteur;
	private boolean isRunning;
	}
